//
//  NewAddShopViewController.m
//  GetPowerDBO
//
//  Created by 周博 on 2017/7/7.
//  Copyright © 2017年 BogoZhou. All rights reserved.
//

#import "NewAddShopViewController.h"
#import "JumpChooseViewController.h"
#import "PickerViewController.h"
#import "ChooseCityViewController.h"
#import "LocalMapViewController.h"
#import "TakePicDelegate.h"
#import "BGTextView.h"

@interface NewAddShopViewController ()<JumpChooseViewControllerDelegate,PickerViewControllerDelegate,ChooseCityViewControllerDelegate,LocalMapViewControllerDelegate,TakePicDelegateDelegate,UITextViewDelegate>
{
    BOOL _isYes;
    
    NSString *_shopPlaceId;
    
    NSString *_shopFromId;
    
    NSString *_pName;
    NSString *_cName;
    NSString *_aName;
    NSString *_pId;
    NSString *_cId;
    NSString *_aId;
    
    NSString *_latitude;
    NSString *_longitude;
    
    NSString *_imageUrl;
}

@property (nonatomic,strong) BGTextView *textView;
@end

@implementation NewAddShopViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self UISetting];
}

- (void)UISetting{
    _isYes = YES;
    _buttonSave.layer.masksToBounds = YES;
    _buttonSave.layer.cornerRadius = 10;
    
    _layoutWidth.constant = kScreenSize.width;
    _layoutHeight.constant = 840;
    
    [self creatTextView];
    
    if (_jumpType.integerValue == 1) {
        [self settingInfo];
    }else{
        _pName = [[NSUserDefaults standardUserDefaults] valueForKey:@"pName"];
        _pId = [[NSUserDefaults standardUserDefaults] valueForKey:@"pId"];
        _cName = [[NSUserDefaults standardUserDefaults] valueForKey:@"cName"];
        _cId = [[NSUserDefaults standardUserDefaults] valueForKey:@"cId"];
        _aName = [[NSUserDefaults standardUserDefaults] valueForKey:@"aName"];
        _aId = [[NSUserDefaults standardUserDefaults] valueForKey:@"aId"];
        
        if (![BGFunctionHelper isNULLOfString:_pName]) {
            _labelProvince.text = [NSString stringWithFormat:@"%@-%@-%@",_pName,_cName,_aName];
        }
        
        _shopFromId = @"0";
    }
    
    UITapGestureRecognizer *recognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(touchScrollView)];
    [recognizer setNumberOfTapsRequired:1];
    [recognizer setNumberOfTouchesRequired:1];
    [_scrollView addGestureRecognizer:recognizer];
}

- (void)touchScrollView
{
    [self.view endEditing:YES];
}


//若是更改店铺信息,调用此方法
- (void)settingInfo{
    _textFieldShopName.text = _model.name;
    
    _labelShopPlace.text = _model.position_name;
    _shopPlaceId = _model.position;
    
    _shopFromId = _model.from_type;
    
    [self chooseFromImageByFromId:_shopFromId];
    
    _textFieldMer.text = _model.contact;
    
    _textFieldMerTel.text = _model.tel;
    
    _pName = _model.province_name;
    _pId = _model.province_id;
    _cName = _model.city_name;
    _cId = _model.city_id;
    _aName = _model.area_name;
    _aId = _model.area_id;
    _labelProvince.text = [NSString stringWithFormat:@"%@-%@-%@",_pName,_cName,_aName];
    
    _latitude = _model.latitude;
    _longitude = _model.longitude;
    _labelAddressNum.text = [NSString stringWithFormat:@"%@-%@",_latitude,_longitude];
    
    _textFieldAddress.text = _model.specific_address;
    
    _textView.text = [BGFunctionHelper isNULLOfString:_model.remark] ? @"" : _model.remark;
    
    _imageUrl = _model.img_url;
    [_imageViewChoose sd_setImageWithURL:[NSURL URLWithString:_imageUrl] placeholderImage:[UIImage imageNamed:@""]];
}

#pragma mark - 点击事件

- (IBAction)backButtonClick:(UIButton *)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

//选择场所
- (IBAction)chooseShopPlaceButtonClick:(UIButton *)sender {
    [self.view endEditing:YES];
    UIStoryboard *storyboard = kMainStroyboard;
    JumpChooseViewController *jumpVC = [storyboard instantiateViewControllerWithIdentifier:@"JumpChooseViewController"];
    jumpVC.modalPresentationStyle = UIModalPresentationOverFullScreen;
    jumpVC.delegate = self;
    [self presentViewController:jumpVC animated:YES completion:nil];
}

////选择店铺来源
//- (IBAction)chooseShopFromButtonClick:(UIButton *)sender {
////    kAlert(@"选择店铺来源");
//    [self.view endEditing:YES];
//    UIStoryboard *storyboard = kMainStroyboard;
//    PickerViewController *pickerView = [storyboard instantiateViewControllerWithIdentifier:@"PickerViewController"];
//    pickerView.dataArray = @[@"自谈",@"第三方合作"];
//    pickerView.type = @"2";
//    pickerView.delegate = self;
//    pickerView.modalPresentationStyle = UIModalPresentationOverFullScreen;
//    [self presentViewController:pickerView animated:YES completion:nil];
//}


//选择店铺来源
- (IBAction)newChooseShopFromButtonClick:(UIButton *)sender {
    if (sender.tag == 1001) {//自谈
        _shopFromId = @"0";
    }else{//第三方合作
        _shopFromId = @"1";
    }
    [self chooseFromImageByFromId:_shopFromId];

}

- (void)chooseFromImageByFromId:(NSString *)fromId{
    if (_shopFromId.integerValue == 0) {//自谈
        _imageViewFromLeft.image = [UIImage imageNamed:@"xuanzhonglv"];
        _imageViewFromRight.image = [UIImage imageNamed:@"xuanzhonghui"];
    }else{//第三方合作
        _imageViewFromRight.image = [UIImage imageNamed:@"xuanzhonglv"];
        _imageViewFromLeft.image = [UIImage imageNamed:@"xuanzhonghui"];
    }
}


//选择省市
- (IBAction)chooseProvinceButtonClick:(UIButton *)sender {
//    kAlert(@"选择省市");
    [self.view endEditing:YES];
    ChooseCityViewController *chooseCityVC = [[ChooseCityViewController alloc] init];
    chooseCityVC.modalPresentationStyle =UIModalPresentationOverFullScreen;
    chooseCityVC.delegate = self;
    [self presentViewController:chooseCityVC animated:YES completion:nil];
}

//选择地理位置
- (IBAction)choosePlaceNumButtonClick:(UIButton *)sender {
//    kAlert(@"选择地理位置");
    [self.view endEditing:YES];
    UIStoryboard *storyboard = kMainStroyboard;
    LocalMapViewController *mapView = [storyboard instantiateViewControllerWithIdentifier:@"LocalMapViewController"];
    mapView.delegate = self;
    [self presentViewController:mapView animated:YES completion:nil];
}

//选择商铺图片
- (IBAction)chooseImageButtonClick:(UIButton *)sender {
//    kAlert(@"选择商铺图片");
    [self.view endEditing:YES];
    [[TakePicDelegate defaultManager] jumpAlarmInViewController:self type:@"0" delegate:self];
}

//保存用户信息
- (IBAction)saveInfoButtonClick:(UIButton *)sender {
//    kAlert(@"保存信息");
    [self.view endEditing:YES];
    if (![self checkNull]) {
        return;
    }
    if (_jumpType.integerValue == 1) {
        //更新
        [self updateData];
    }else{
        //上传
        [self uploadData];
    }
    
}

//点击打钩按钮
- (IBAction)chooseYesButtonClick:(UIButton *)sender {
//    kAlert(@"点击打钩按钮");
    [self.view endEditing:YES];
    _isYes = !_isYes;
    if (_isYes) {
        [_buttonSave setBackgroundColor:kGreenColor];
        [_buttonSave setTitleColor:kWhiteColor forState:UIControlStateNormal];
        _buttonSave.enabled = YES;
        _imageViewChoose.image = [UIImage imageNamed:@"xuanzhong"];
    }else{
        [_buttonSave setBackgroundColor:kColorFrom0x(0xbebebe)];
        [_buttonSave setTitleColor:kWhiteColor forState:UIControlStateNormal];
        _buttonSave.enabled = NO;
        _imageViewChoose.image = [UIImage imageNamed:@"weixuan"];
    }
}

#pragma mark - 创建textView

- (void )creatTextView{
    
    _textView = [[BGTextView alloc] initWithFrame:CGRectMake(10, 10, kScreenSize.width - 20, _viewTextView.sizeHeight - 20)];
    _textView.textFont = [UIFont systemFontOfSize:15];
    if ([BGFunctionHelper isNULLOfString:_model.remark]) {
        _textView.placeholderStr = @"备注可留空";
    }else{
        _textView.placeholderStr = @"";
    }
    _textView.placeholderColor = kColorFrom0x(0xbebebe);
    _textView.textViewTextColor = [UIColor blackColor];
    _textView.backgroundColor = kColorFrom0x(0xf4f4f4);
    
    _textView.tintColor = [UIColor blackColor];
    //    _textView.keyboardType = UIKeyboardTypeNumberPad;
    [_textView updateInfo];
    _textView.delegate = self;
    [_viewTextView addSubview:_textView];
}


- (void)textViewDidChange:(UITextView *)textView{
    [_textView textViewDidChange:textView];
}

#pragma mark - 网络请求

- (void)uploadData{
    NSLog(@"增加");
    self.hub = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    // Set the label text.
    self.hub.label.text = NSLocalizedString(@"加载中...", @"HUD loading title");
    [[AFClient shareInstance] newShopInfoByEid:kUserId name:_textFieldShopName.text contact:_textFieldMer.text tel:_textFieldMerTel.text latitude:_latitude longitude:_longitude province_id:_pId city_id:_cId area_id:_aId specific_address:_textFieldAddress.text province_name:_pName city_name:_cName area_name:_aName position:_shopPlaceId position_name:_labelShopPlace.text img_url:_imageUrl from_type:_shopFromId remark:_textView.text progressBlock:nil success:^(id responseBody) {
        [self.hub hideAnimated:YES];
        if ([responseBody[@"code"] integerValue] == 200) {
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"门店创建成功" message:nil preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [self.navigationController popViewControllerAnimated:YES];
            }];
            
            [alert addAction:action];
            [self presentViewController:alert animated:YES completion:nil];
        }else{
            kAlert(responseBody[@"message"]);
        }
    } failure:^(NSError *error) {
        [self.hub hideAnimated:YES];
    }];
}

- (void)updateData{
    NSLog(@"更新");
    [self.hub hideAnimated:YES];
    self.hub = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    // Set the label text.
    self.hub.label.text = NSLocalizedString(@"加载中...", @"HUD loading title");
    [[AFClient shareInstance] updateShopInfoByShopId:_model.id eid:kUserId name:_textFieldShopName.text contact:_textFieldMer.text tel:_textFieldMerTel.text latitude:_latitude longitude:_longitude province_id:_pId city_id:_cId area_id:_aId specific_address:_textFieldAddress.text province_name:_pName city_name:_cName area_name:_aName position:_shopPlaceId position_name:_labelShopPlace.text img_url:_imageUrl from_type:_shopFromId remark:_textView.text progressBlock:nil success:^(id responseBody) {
        [self.hub hideAnimated:YES];
        if ([responseBody[@"code"] integerValue] == 200) {
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"门店信息更新成功" message:nil preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [self.navigationController popViewControllerAnimated:YES];
            }];
            
            [alert addAction:action];
            [self presentViewController:alert animated:YES completion:nil];
        }else{
            kAlert(responseBody[@"message"]);
        }
    } failure:^(NSError *error) {
        [self.hub hideAnimated:YES];
    }];
}

- (BOOL)checkNull{
    if ([BGFunctionHelper isNULLOfString:_textFieldShopName.text]) {
        kAlert(@"请输入店铺名");
        return NO;
    }
    if ([BGFunctionHelper isNULLOfString:_labelShopPlace.text]) {
        kAlert(@"请选择店铺所在场所");
        return NO;
    }

    if ([BGFunctionHelper isNULLOfString:_textFieldMer.text]) {
        kAlert(@"请输入联系人");
        return NO;
    }
    if ([BGFunctionHelper isNULLOfString:_textFieldMerTel.text]) {
        kAlert(@"请输入联系号码");
        return NO;
    }
    if ([BGFunctionHelper isNULLOfString:_labelProvince.text]) {
        kAlert(@"请选择省市");
        return NO;
    }
    if ([BGFunctionHelper isNULLOfString:_labelAddressNum.text]) {
        kAlert(@"请选择地理位置");
        return NO;
    }
    if ([BGFunctionHelper isNULLOfString:_textFieldAddress.text]) {
        kAlert(@"请输入详细地址");
        return NO;
    }
    if (_jumpType.integerValue == 2) {
        if ([BGFunctionHelper isNULLOfString:_imageUrl]) {
            kAlert(@"请选择图片");
            return NO;
        }
    }
    return YES;
}

#pragma mark - 代理方法

//获取选择的商铺场所
- (void)getShopPlaceInfoShopPlaceString:(NSString *)shopPlaceString shopPlaceId:(NSString *)shopPlaceId{
    _labelShopPlace.text = shopPlaceString;
    _shopPlaceId = shopPlaceId;
}

//获取省市区
- (void)getShopProvinceName:(NSString *)provinceName pId:(NSString *)pId cityName:(NSString *)cityName cityId:(NSString *)cityId areaName:(NSString *)areaName areaId:(NSString *)areaId{
    _labelProvince.text = [NSString stringWithFormat:@"%@-%@-%@",provinceName,cityName,areaName];
    
    _pName = provinceName;
    _pId = pId;
    
    _cName = cityName;
    _cId = cityId;
    
    _aName = areaName;
    _aId = areaId;
    
    [[NSUserDefaults standardUserDefaults] setValue:_pName forKey:@"pName"];
    [[NSUserDefaults standardUserDefaults] setValue:_pId forKey:@"pId"];
    [[NSUserDefaults standardUserDefaults] setValue:_cName forKey:@"cName"];
    [[NSUserDefaults standardUserDefaults] setValue:_cId forKey:@"cId"];
    [[NSUserDefaults standardUserDefaults] setValue:_aName forKey:@"aName"];
    [[NSUserDefaults standardUserDefaults] setValue:_aId forKey:@"aId"];
    
    

}

//获取坐标
- (void)getShoplLatitude:(NSString *)latitude longitude:(NSString *)longitude{
    _labelAddressNum.text = [NSString stringWithFormat:@"%@,%@",latitude,longitude];
    _latitude = latitude;
    _longitude = longitude;
}

//获取图片
- (void)getShopChooseImage:(UIImage *)image{
    _imageViewChoose.image = image;
    [self upLoadImageByImage:image];
}

- (void)upLoadImageByImage:(UIImage *)image{
    [self.hub hideAnimated:YES];
    
    self.hub = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    // Set the label text.
    self.hub.label.text = NSLocalizedString(@"加载中...", @"HUD loading title");
    [[AFClient shareInstance] uploadImageByImage:image progressBlock:nil success:^(id responseBody) {
        [self.hub hideAnimated:YES];
        if ([responseBody[@"code"] integerValue] == 200) {
            _imageUrl = responseBody[@"data"];
        }else{
            kAlert(responseBody[@"message"]);
        }
    } failure:^(NSError *error) {
        [self.hub hideAnimated:YES];
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
